import json
import os

from markdown.api_doc_model import ApiDoc, DataModel

"""
Author: Gaoqiang Du
Description：将apifox导出的配置文件转成一套markdown文件
Time: 2022/4/19 13:57
"""


def mkdir(path):
    if not os.path.exists(path):
        os.mkdir(path)

    return path


def save_doc(save_path, doc):
    with open(save_path, "w", encoding="utf8") as f:
        f.write(doc)


def save_doc_markdowns(save_path, doc_dict):
    for i in doc_dict["items"]:
        save_doc(os.path.join(save_path, i["name"] + ".md"), i["content"])

    for child in doc_dict["children"]:
        save_doc_markdowns(os.path.join(save_path, child["name"]), child)


def save_markdown(save_path, api_title, api_dict, data_mod=None):
    doc = ApiDoc(
        title=api_title, description=api_dict["description"],
        req_method=api_dict["method"], path=api_dict["path"],
        req_params=api_dict["parameters"].get("query"),
        data_mod=data_mod
    )

    for example in api_dict["responseExamples"]:
        if "成功" in example["name"]:
            doc.res_example = example["data"]
            break

    for res in api_dict["responses"]:
        if "成功" in res["name"] and res.get("jsonSchema"):
            doc.res_json = res["jsonSchema"]["properties"]
            break

    with open(os.path.join(save_path, api_title + ".md"), "w", encoding="utf8") as f:
        f.write(doc.format_to_markdown())


def parser_apifox_file(save_path, items: list, data_mod=None):
    for i in items:
        name = i["name"]
        if i.get("items") is not None:
            parser_apifox_file(
                mkdir(os.path.join(save_path, name)),
                i["items"],
                data_mod
            )
        else:
            save_markdown(save_path, name, i["api"], data_mod)


def reverse_apifox_file_to_markdown(api_file_path, save_path):
    with open(api_file_path, "r", encoding="utf8") as f:
        proj_json = json.load(f)

    # 读取数据模型
    data_mod = DataModel()
    if proj_json["schemaCollection"]:
        data_mod.from_apifox(proj_json["schemaCollection"][0]["items"])

    proj_name = proj_json["info"]["name"]
    root = proj_json["apiCollection"][0]
    root_dir = mkdir(os.path.join(save_path, proj_name))
    parser_apifox_file(root_dir, root["items"], data_mod)

    # 添加非接口文档的保存
    if proj_json["docCollection"]:
        doc_root = proj_json["docCollection"][0]
        save_doc_markdowns(root_dir, doc_root)


if __name__ == '__main__':
    apifox_file_path = "apifox.json"
    save_dir = "api"
    reverse_apifox_file_to_markdown(apifox_file_path, save_dir)
